// pages/qna/result.js
const app = getApp();
const api = require('../../common/js/api');
const conf = require('../../app.config')
import regeneratorRuntime from '../../common/js/plugin/runtime.js'
const VC = require("../../common/js/plugin/VCanvas.js");
const {
    ScanQRcode,
    Qrcodelength,
    tagOperation
  } = require('../../common/js/utils.js')
Page({

    data: {
        statusBarHeight: app.globalData.statusBarHeight,
        scanTabHeight: '',//tab高度
        cdn: 'https://crm.stdfood.com.cn/duoli/crm/qna',
        v: '0.0.7',
        userinfo:{},
        resultData:{},
    },

    onLoad: function (options) {
        this.setData({
            cdn: 'https://crm.stdfood.com.cn/duoli/crm/qna'
        })
    },
    onShow: function(){
      let that = this 
      that.api.interface.getCustomerInfo().then(res=>{
        wx.setStorageSync('userinfo', res.data.data)
        that.setData({
          userinfo: res.data.data
        })
      })
      this.initResult()

    },
    initResult() {
        let that = this
        let parm1 = wx.getStorageSync('answerlist')
        that.api.interface.submitActivityAnswer(parm1).then(res=>{
            if(res.data.code == 200){
                this.setData({ resultData: res.data.data })
            }else if(res.data.code == 1 ) {
                this.api.interface.getActivityAnswerLog().then(res=>{
                    console.log(res,200)
                    if (res.data.code == 200) {
                          this.setData({ resultData: res.data.data })
                      }else
                          app.alert(res.data.message)
                })
            }
        })
   
    },

    noMoveEvent(e) {
        return false
    },

    // 初始化
    init(res) {
        console.log(res)
        this.canvas = res[0].node
        this.ctx = this.canvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        //新接口需显示设置画布宽高；
        this.canvas.width = res[0].width * dpr
        this.canvas.height = res[0].height * dpr
        this.ctx.scale(dpr, dpr);
    },

    saveImage() {
        console.log(11111111111)
        // 保存到相册
        wx.canvasToTempFilePath({
            canvas: this.canvas, x: 0, y: 0,
            width: this.canvas.width,
            height: this.canvas.height,
            destWidth: this.canvas.width,     //截取canvas的宽度
            destHeight: this.canvas.height,   //截取canvas的高度
            success: function (res) {
                console.log('生成图片成功：', res)
                wx.saveImageToPhotosAlbum({  //保存图片到相册
                    filePath: res.tempFilePath,
                    success: function () {
                        wx.showToast({
                            title: "保存图片成功！",
                            duration: 2000
                        })
                    }
                })
            },
        }, this)

    },

    async onBuild() {
        let that = this
        console.log(wx.getStorageSync('userinfo').nickName,11111111111)
        wx.pitaya.sendEvent('投喂朋友圈')
        app.loading.show('海报合成中')
        let this_ = this,
            _u = this.data.cdn,
            imgs = { bg: '', head: '', g1: '', g2: '', qr: '' },
            w = 750, h = 1447,
            nick = wx.getStorageSync('userinfo').nickName,
            xg = this.data.resultData.randomStr[1][0] + '、' + this.data.resultData.randomStr[1][1],
            zy = this.data.resultData.randomStr[2][0],
            ms = this.data.resultData.randomStr[3][0] + '、' + this.data.resultData.randomStr[3][1],
            dd = this.data.resultData.randomStr[4][0]

        imgs.bg = await this.downloadImg(_u + '/build-bg.jpg?v=' + that.data.v)
        imgs.item = await this.downloadImg(_u + '/build/head.png?v=' + that.data.v)
        imgs.head = await this.downloadImg(wx.getStorageSync('userinfo').headimgurl)
        imgs.txt = await this.downloadImg(_u + '/build/txt.png?v=' + that.data.v)
        imgs.g1 = await this.downloadImg(_u + '/build/product.png?v=' + that.data.v)
        imgs.g2 = await this.downloadImg(_u + '/build/product.png?v=' + that.data.v)
        imgs.box = await this.downloadImg(_u + '/build/qrcode.png?v=' + that.data.v)
        imgs.qr = await this.downloadImg(_u + '/build/qr.png?v=' + that.data.v)

        let name = nick.length > 9 ? nick.substring(0, 9) + '...' : nick
        let params = [
            { type: 'image', path: imgs.bg.path, width: w, height: h, x: 0, y: 0, name: "bg" },
            { type: 'image', path: imgs.item.path, width: 540, height: 162, x: 56, y: 50, name: 'item' },
            { type: 'image', path: imgs.head.path, fillType: 'circle', width: 131, height: 131, x: 62, y: 74, name: 'head' },
            { type: 'image', path: imgs.txt.path, width: 588, height: 310, x: 76, y: 248, name: 'txt' },
            { type: 'image', path: imgs.box.path, width: 524, height: 223, x: 170, y: 1087, name: 'box' },
            { type: 'image', path: imgs.qr.path, width: 179, fillType: 'circle', height: 179, x: 494, y: 1108, name: 'qr' },
            // 昵称1
            { type: 'text', text: name, width: 390, x: 216, y: 95, color: "#fff", fontSize: 38 },
            // 性格
            { type: 'text', text: xg, width: 202, x: 285, y: 248, color: "#fff", fontSize: 32, align: 'center' },
            // 职业
            { type: 'text', text: zy, width: 160, x: 88, y: 295, color: "#fff", fontSize: 32, align: 'center' },
            // 美食
            { type: 'text', text: ms, width: 360, x: 88, y: 409, color: "#fff", fontSize: 32, align: 'center' },
            // 地点
            { type: 'text', text: dd, width: 240, x: 244, y: 465, color: "#fff", fontSize: 32, align: 'center' }
        ]

        if (this.data.resultData.list && this.data.resultData.list.length > 0) {
            let list = this.data.resultData.list
            if (list.length > 1) {
                let g1 = await this.downloadImg(list[0].pic),
                    g2 = await this.downloadImg(list[1].pic)

                let cnt1 = list[0].content.length > 40 ? list[0].content.substring(0, 40) + '...' : list[0].content,
                    cnt2 = list[1].content.length > 40 ? list[1].content.substring(0, 40) + '...' : list[1].content
                params.push(
                    { type: 'image', path: imgs.g1.path, width: 639, height: 155, x: 56, y: 672, name: 'g1bg' },
                    { type: 'image', path: g1.path, width: 200, height: 141, x: 100, y: 679, name: 'g1' },
                    { type: 'text', text: list[0].name, width: 180, x: 314, y: 679, color: "#fff", fontSize: 25, wordWrap: true },
                    { type: 'text', text: cnt1, width: 370, x: 314, y: 727, color: "#fff", fontSize: 25, wordWrap: true },

                    { type: 'image', path: imgs.g2.path, width: 639, height: 155, x: 56, y: 861, name: 'g2bg' },
                    { type: 'image', path: g2.path, width: 200, height: 141, x: 100, y: 868, name: 'g2' },
                    { type: 'text', text: list[1].name, width: 180, x: 314, y: 868, color: "#fff", fontSize: 25, wordWrap: true },
                    { type: 'text', text: cnt2, width: 370, x: 314, y: 916, color: "#fff", fontSize: 25, wordWrap: true },
                )
            } else {
                let g1 = await this.downloadImg(list[0].pic)
                let cnt1 = list[0].content.length > 48 ? list[0].content.substring(0, 48) : list[0].content
                params.push(
                    { type: 'image', path: imgs.g1.path, width: 639, height: 155, x: 56, y: 672, name: 'g1bg' },
                    { type: 'image', path: g1.path, width: 141, height: 141, x: 100, y: 679, name: 'g1' },
                    { type: 'text', text: list[0].name, width: 180, x: 314, y: 678, color: "#fff", fontSize: 25, wordWrap: true },
                    { type: 'text', text: cnt1, width: 370, x: 314, y: 727, color: "#fff", fontSize: 25, wordWrap: true },
                )
            }
        }

        let stage = new VC.Stage(wx.createCanvasContext('icvs'), w, h, {
            onDraw: () => {
                app.loading.hide()
                wx.canvasToTempFilePath({
                    x: 0, y: 0, width: w, height: h, destWidth: w, destHeight: h, fileType: 'jpg',
                    canvasId: 'icvs',
                    success: (res) => {
                        wx.saveImageToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success(data) { wx.showToast({ title: '已保存到相册' }) },
                            fail: function (data) { app.alert('请打开设置并同意授权保存图片') }
                        });
                    }
                })
            }
        });
        stage.addChildByList(params);
        stage.update();
    },

    onOpenApp(e) {
        // let { id, path } = e.currentTarget.dataset
        // wx.navigateToMiniProgram({
        //     appId: id,
        //     path: path,
        //     success: () => { }
        // })
        wx.navigateTo({ url: '../store/store?initType=新客首单福利' })
    },
    onGoback() {
        wx.requestSubscribeMessage({
            tmplIds: ["vUCAXpjImMVfwxPDJ-_0GUQsZut9nIWp5nA388ppsNc"],
          success:res=>{
            this.api.interface.userSubscribeMessage({type: 4});
          },
          complete(){
            wx.reLaunch({
                url: '../home/home'
              })
          }
        })
      
    },
    async drawImg(url, setting) {
        let this_ = this,
            obj = await this.downloadImg(url)
        console.log('download ===> ', obj)
        return new Promise((resolve, reject) => {
            let img = this_.canvas.createImage();
            img.src = obj.path;
            img.onload = () => {
                if (setting.circular) {
                    this_.ctx.arc(setting.left, setting.top, setting.width / 2, 0, 2 * Math.PI)
                    this_.ctx.clip();
                }
                this_.ctx.drawImage(img, setting.left || 0, setting.top || 0, setting.width || obj.width, setting.height || obj.height);
                this_.ctx.restore();
                resolve()
            };
        })
    },

    async drawTxt(txt, setting) {
        let this_ = this
        this_ctx.font = setting.font;
        this_ctx.fillStyle = setting.color;
        if (setting.maxWidth)
            this_ctx.fillText(txt, setting.left, setting.top, setting.maxWidth)
        else
            this_ctx.fillText(txt, setting.left, setting.top)
    },


    downloadImg(_path) {
        return new Promise((resolve, reject) => {
            wx.getImageInfo({
                src: _path,
                success: (imgInfoRes) => { resolve(imgInfoRes) },
                fail: (err) => { resolve(err) },
            })
        })
    },

    onShareAppMessage() {
        let share = {
            title: '测一测你的投喂指南',
            path: '/pages/qna/index',
            imageUrl:'../../common/images/share.png'
        }
        tagOperation(1,3)
        return share
    },
})